<script setup>
// 这里可以添加组件逻辑（如果需要）
</script>

<template>
  <div class="teacher-container">
    <div class="page-header">
      <h1>教师管理中心</h1>
    </div>
    
    <el-row :gutter="20">
      <el-col :span="8">
        <div class="card">
          <div class="user-info">
            <div class="avatar">{{ userInitials }}</div>
            <h2>{{ user.name }}</h2>
            <div class="user-meta">
              <p><i class="el-icon-school"></i> {{ user.universityName }}</p>
              <p><i class="el-icon-office-building"></i> {{ user.collegeName }}</p>
              <p><i class="el-icon-notebook-2"></i> {{ user.majorName }}</p>
            </div>
            <el-button type="primary" size="small" @click="showEditDialog">编辑个人信息</el-button>
          </div>
        </div>
      </el-col>
      
      <el-col :span="16">
        <div class="card mb-20">
          <div class="card-header">
            <h3>学生列表</h3>
            <div>
              <el-input
                placeholder="搜索学生"
                v-model="searchQuery"
                class="search-input"
                prefix-icon="el-icon-search"
                clearable
                @clear="loadStudents"
              ></el-input>
              <el-button type="primary" size="small" @click="searchStudents">搜索</el-button>
            </div>
          </div>
          
          <div v-if="loading" class="loading">
            <el-skeleton :rows="5" animated></el-skeleton>
          </div>
          
          <div v-else-if="students.length === 0" class="empty-state">
            <el-empty description="暂无学生数据"></el-empty>
          </div>
          
          <el-table v-else :data="students" style="width: 100%">
            <el-table-column prop="userId" label="学号" width="120"></el-table-column>
            <el-table-column prop="name" label="姓名" width="100"></el-table-column>
            <el-table-column prop="universityName" label="大学"></el-table-column>
            <el-table-column prop="collegeName" label="学院"></el-table-column>
            <el-table-column prop="majorName" label="专业"></el-table-column>
            <el-table-column prop="classId" label="班级" width="100"></el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button 
                  type="text" 
                  size="small" 
                  @click="viewStudentResults(scope.row)"
                >查看测试</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
            ></el-pagination>
          </div>
        </div>
        
        <!-- 学生测试结果 -->
        <div v-if="selectedStudent" class="card">
          <div class="card-header">
            <h3>{{ selectedStudent.name }} 的测试结果</h3>
            <el-button size="small" @click="selectedStudent = null">返回</el-button>
          </div>
          
          <div v-if="loadingResults" class="loading">
            <el-skeleton :rows="3" animated></el-skeleton>
          </div>
          
          <div v-else-if="studentResults.length === 0" class="empty-state">
            <el-empty description="该学生暂无测试记录"></el-empty>
          </div>
          
          <el-table v-else :data="studentResults" style="width: 100%">
            <el-table-column prop="id" label="ID" width="80"></el-table-column>
            <el-table-column prop="testTime" label="测试时间">
              <template slot-scope="scope">
                {{ formatDate(scope.row.testTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="mbtiType" label="MBTI类型" width="100"></el-table-column>
            <el-table-column prop="typeName" label="类型名称" width="120"></el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button 
                  type="text" 
                  size="small" 
                  @click="viewResult(scope.row)"
                >查看详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
    
    <!-- 编辑个人信息对话框 -->
    <el-dialog title="编辑个人信息" :visible.sync="editDialogVisible" width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="大学名称" prop="universityName">
          <el-input v-model="editForm.universityName"></el-input>
        </el-form-item>
        <el-form-item label="学院名称" prop="collegeName">
          <el-input v-model="editForm.collegeName"></el-input>
        </el-form-item>
        <el-form-item label="专业名称" prop="majorName">
          <el-input v-model="editForm.majorName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="editForm.password" placeholder="不修改请留空"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateUserInfo">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Teacher',
  data() {
    return {
      user: {
        userId: '',
        name: '',
        universityName: '',
        collegeName: '',
        majorName: ''
      },
      students: [],
      studentResults: [],
      selectedStudent: null,
      loading: true,
      loadingResults: false,
      editDialogVisible: false,
      searchQuery: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      editForm: {
        name: '',
        universityName: '',
        collegeName: '',
        majorName: '',
        password: ''
      },
      editRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        universityName: [
          { required: true, message: '请输入大学名称', trigger: 'blur' }
        ],
        collegeName: [
          { required: true, message: '请输入学院名称', trigger: 'blur' }
        ],
        majorName: [
          { required: true, message: '请输入专业名称', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    userInitials() {
      if (!this.user.name) return '?'
      return this.user.name.substring(0, 1)
    }
  },
  created() {
    this.loadUserInfo()
  },
  methods: {
    loadUserInfo() {
      const userStr = localStorage.getItem('user')
      if (!userStr) {
        this.$message.error('用户未登录')
        this.$router.push('/admin/login')
        return
      }
      
      try {
        const userData = JSON.parse(userStr)
        this.user.userId = userData.userId
        
        // 获取用户详情
        this.$http.get(`/api/users/${userData.userId}`)
          .then(response => {
            const { code, data } = response.data
            
            if (code === 200 && data) {
              this.user = data
              this.loadStudents()
            } else {
              this.$message.error('获取用户信息失败')
            }
          })
          .catch(error => {
            console.error('获取用户信息失败:', error)
            this.$message.error('获取用户信息失败，请检查网络连接')
          })
      } catch (e) {
        console.error('解析用户信息失败:', e)
        this.$message.error('用户信息无效')
        this.$router.push('/admin/login')
      }
    },
    
    loadStudents() {
      this.loading = true
      
      this.$http.get(`/api/users/teachers/${this.user.userId}/students`)
        .then(response => {
          const { code, data } = response.data
          
          if (code === 200 && data) {
            this.students = data
            this.total = data.length
          } else {
            this.$message.error('获取学生列表失败')
          }
        })
        .catch(error => {
          console.error('获取学生列表失败:', error)
          this.$message.error('获取学生列表失败，请检查网络连接')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    searchStudents() {
      if (!this.searchQuery.trim()) {
        this.loadStudents()
        return
      }
      
      this.loading = true
      
      // 使用查询参数搜索学生
      this.$http.get('/api/users', {
        params: {
          page: this.currentPage,
          size: this.pageSize,
          name: this.searchQuery,
          role: 'student'
        }
      })
        .then(response => {
          const { code, data } = response.data
          
          if (code === 200 && data && data.list) {
            this.students = data.list
            this.total = data.total
          } else {
            this.$message.error('搜索学生失败')
          }
        })
        .catch(error => {
          console.error('搜索学生失败:', error)
          this.$message.error('搜索学生失败，请检查网络连接')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    viewStudentResults(student) {
      this.selectedStudent = student
      this.loadingResults = true
      
      this.$http.get(`/api/testresults/byUserId/${student.userId}`)
        .then(response => {
          const { code, data } = response.data
          
          if (code === 200) {
            this.studentResults = data || []
          } else {
            this.$message.error('获取学生测试结果失败')
          }
        })
        .catch(error => {
          console.error('获取学生测试结果失败:', error)
          this.$message.error('获取学生测试结果失败，请检查网络连接')
        })
        .finally(() => {
          this.loadingResults = false
        })
    },
    
    viewResult(result) {
      // 保存测试结果到本地存储
      localStorage.setItem('lastTestResult', JSON.stringify(result))
      
      // 跳转到结果页面
      this.$router.push('/result')
    },
    
    handleSizeChange(size) {
      this.pageSize = size
      this.loadStudents()
    },
    
    handleCurrentChange(page) {
      this.currentPage = page
      this.loadStudents()
    },
    
    showEditDialog() {
      this.editForm = {
        name: this.user.name,
        universityName: this.user.universityName,
        collegeName: this.user.collegeName,
        majorName: this.user.majorName,
        password: ''
      }
      
      this.editDialogVisible = true
    },
    
    updateUserInfo() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          const updateData = { ...this.editForm }
          
          // 如果密码为空，则不更新密码
          if (!updateData.password) {
            delete updateData.password
          }
          
          this.$http.put(`/api/users/${this.user.userId}`, updateData)
            .then(response => {
              const { code, data } = response.data
              
              if (code === 200) {
                this.$message.success('更新成功')
                this.editDialogVisible = false
                
                // 更新本地用户信息
                this.user = { ...this.user, ...updateData }
                delete this.user.password
                
                // 更新localStorage中的用户信息
                const userStr = localStorage.getItem('user')
                if (userStr) {
                  try {
                    const userData = JSON.parse(userStr)
                    userData.name = this.user.name
                    localStorage.setItem('user', JSON.stringify(userData))
                  } catch (e) {
                    console.error('更新本地用户信息失败:', e)
                  }
                }
              } else {
                this.$message.error('更新失败')
              }
            })
            .catch(error => {
              console.error('更新失败:', error)
              this.$message.error('更新失败，请检查网络连接')
            })
        }
      })
    },
    
    formatDate(dateStr) {
      if (!dateStr) return '未知时间'
      
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.teacher-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 24px;
  color: #303133;
}

.card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  font-size: 18px;
  color: #303133;
  margin: 0;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: #409EFF;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 36px;
  margin-bottom: 15px;
}

.user-info h2 {
  font-size: 20px;
  margin-bottom: 15px;
  color: #303133;
}

.user-meta {
  margin-bottom: 20px;
  width: 100%;
}

.user-meta p {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  color: #606266;
}

.user-meta i {
  margin-right: 8px;
  color: #909399;
}

.loading {
  padding: 20px 0;
}

.empty-state {
  padding: 30px 0;
  text-align: center;
}

.search-input {
  width: 200px;
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>